package com.zprmb.udzt.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zprmb.udzt.BaseActivity;
import com.zprmb.udzt.R;
import com.zprmb.udzt.bean.LoadingResult0;
import com.zprmb.udzt.bean.ZhiTouNewBean;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.myloading.AVLoadingIndicatorView;
import com.zprmb.udzt.myloading.indicators.BallSpinFadeLoaderIndicator;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.TimeCount;
import com.zprmb.udzt.util.VolleryUtil3;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author shenshao
 */

public class LoadingActivity2 extends BaseActivity implements View.OnClickListener {

    /*TabLayout mTabLayout;
    ViewPager mViewPager;

    SpinKitView spinKitView;*/
    private int i = 0;
    private int TIME = 5000;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                handler.postDelayed(this, TIME);
                invest();
                System.out.println("do...");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("exception...");
            }
        }
    };

    TextView tv_title;
    private AVLoadingIndicatorView avi;
    private TimeCount timeCount;
    TextView text_time;
    //返回按钮
    ImageView img_back;

    TextView text_wait;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        timer.cancel();
        return super.onKeyDown(keyCode, event);
    }

    CountDownTimer timer = new CountDownTimer(30000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            //每隔countDownInterval秒会回调一次onTick()方法
//                Log.d(TAG, "onTick  " + millisUntilFinished / 1000);
            text_time.setText("" + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
//                Log.d(TAG, "onFinish -- 倒计时结束");
            avi.hide();
            startActivity(new Intent(LoadingActivity2.this, FailActivity2.class));
            handler.removeCallbacks(runnable);
            timer.cancel();
            finish();

        }
    }.start();
    String str_receive;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("等待中...");
        text_time = (TextView) findViewById(R.id.text_time);
        handler.postDelayed(runnable, TIME); //每隔1s执行
        avi = (AVLoadingIndicatorView) findViewById(R.id.avi);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(this);
        text_wait = (TextView) findViewById(R.id.text_wait);
        //text_result
        str_receive = getIntent().getStringExtra("biaoji");
        text_wait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoadingActivity2.this, SuccessActivity2.class));
//                timer.onFinish();
                timer.cancel();
                finish();
                handler.removeCallbacks(runnable);
                LoadingActivity2.this.finish();
            }
        });


        //timer.cancel(); // 取消


        BallSpinFadeLoaderIndicator indicator1 = new BallSpinFadeLoaderIndicator();
//        avi.setIndicatorColor(R.color.coloryellow);

        avi.setIndicator(indicator1);


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Long time = new Long(445555555);
        String d = format.format(time);
        try {
            Date date = format.parse(d);
            Log.d(d, "44444444444");

        } catch (
                ParseException e)

        {
            e.printStackTrace();
        }

    }

    /**
     * 投资
     */
    private void invest() {
        AjaxParams params = new AjaxParams();

//        params.put("couponId", getIntent().getStringExtra("couponId"));
        params.put("orderId", getIntent().getStringExtra("orderId"));
        Log.e("投资", params.toString());

        VolleryUtil3 vollery = new VolleryUtil3() {
            @Override
            public void onUpDate(final JSONObject jsonObject) {
                // TODO Auto-generated method stub
                Log.e("invest", jsonObject.toString());
                JSONObject jsonObject1 = jsonObject.optJSONObject("data");
                String string = jsonObject1.optString("productType");
                if (jsonObject.optInt("success") == 1) {
                    Gson gson = new Gson();
                    ZhiTouNewBean mySucces1 = new ZhiTouNewBean();
                    mySucces1 = gson.fromJson(jsonObject.toString(), ZhiTouNewBean.class);
//起始时间
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Long time = new Long(mySucces1.getData().getCountRateTime_ztb());
                    Long time2 = new Long(mySucces1.getData().getDueTime_ztb());
                    String d = format.format(time);

                    String e = format.format(time2);
//                        Date date = format.parse(d);
                    Intent intent = new Intent(LoadingActivity2.this, com.zprmb.udzt.activity.SuccessActivity2.class);
                    intent.putExtra("qishi", d);
                    intent.putExtra("jieshu", e);
                    intent.putExtra("name", mySucces1.getData().getProductType());
                    intent.putExtra("qitou", mySucces1.getData().getInvestAmount());

                    startActivity(intent);
                    timer.cancel();
//                            timer.onFinish();
                    handler.removeCallbacks(runnable);
                    finish();
                    LoadingActivity2.this.finish();
// /api/v6/invest/waitRequest?couponId=187

                } else if (jsonObject.optInt("success") == 0 && string.equals("ASSET_GOLDEN")) {

                    Gson gson = new Gson();
                    LoadingResult0 loadingResult0 = new LoadingResult0();
                    loadingResult0 = gson.fromJson(jsonObject.toString(), LoadingResult0.class);
                    Intent intent = new Intent(LoadingActivity2.this, FailActivity2.class);
                    intent.putExtra("comment", loadingResult0.getComment());
//                    intent.putExtra("str_receive", str_receive);
                    startActivity(intent);
//                    timer.cancel();
//                    timer.onFinish();

                    handler.removeCallbacks(runnable);
                    timer.cancel();
                    finish();
                    LoadingActivity2.this.finish();
                } else if (jsonObject.optString("code").equals("FAILED")) {
                    Gson gson = new Gson();
                    LoadingResult0 loadingResult0 = new LoadingResult0();
                    loadingResult0 = gson.fromJson(jsonObject.toString(), LoadingResult0.class);
                    Intent intent = new Intent(LoadingActivity2.this, FailActivity2.class);
//                    intent.putExtra("str_receive", str_receive);
                    intent.putExtra("comment", loadingResult0.getComment());
//                    timer.onFinish();
                    timer.cancel();
                    handler.removeCallbacks(runnable);

                    finish();
                    LoadingActivity2.this.finish();
                } else {

                }
            }

            @Override
            public void onError() {


            }
        };

        vollery.setShow(true);
        vollery.setRequestMethod(1);
        vollery.setHeaders("token", getToken());
        vollery.setHeaders("deviceId", getdeviceId());
        vollery.setHeaders("client", "android");
        vollery.execute(this, Constant.URL
                + "/api/v6/invest/investResults?", params.toString());

    }


    @Override
    public void onClick(View v) {

    }
}
